/**
 * Copyright (c) 2012, David Varbel
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.epistrata.neutraltheory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.BitSet;
import java.util.Calendar;
import java.util.List;
import java.util.Map.Entry;

import com.epistrata.experiment.Model;
import com.epistrata.experiment.Run;
import com.epistrata.experiment.View;

/**
 * @author David
 *
 */
public class FileView implements View {
	private BufferedWriter responseOut;
	private boolean headerLineWritten = false;
	private String experimentTimeStamp;
	private final int logPopulationInterval = 50;

	@Override
	public void handleRunFinish(Run run) throws Exception {
		if (run == null) {
			throw new IllegalArgumentException("Run parameter cannot be null.");
		}
		
		StringBuilder factorValues = new StringBuilder();
		for (Entry<String, String> factor : run.getFactors().entrySet()) {
			factorValues.append(factor.getValue() + "\t");
		}

		StringBuilder factorTitles = new StringBuilder();
		if (!headerLineWritten) {
			for (Entry<String, String> factor : run.getFactors().entrySet()) { //TODO how to ensure they will be ordered the same in all runs?
				factorTitles.append(factor.getKey() + "\t");
			}
		}

		synchronized (responseOut) {
			if (!headerLineWritten) {
				responseOut.write("Run\t" + factorTitles + "Mean\tVariance\tDuration\n");
				headerLineWritten = true;
			}

			responseOut.write(Integer.toString(run.getRunNumber()) + "\t" + factorValues + run.getResponses().get("Recent Species Mean") + "\t" + run.getResponses().get("Recent Species Variance") +"\t" + Long.toString(run.getRunDuration()) + "\n");
		}
	}
	
	/**
	 * Only called at end of run.  Stores species count history and population.
	 * 
	 */
	@Override
	public void handleDataUpdate(Run run, Model model) throws Exception {
		if (run == null) {
			throw new IllegalArgumentException("Run parameter cannot be null.");
		}
		if (!(model instanceof NeutralTheoryModel)) {
			throw new IllegalArgumentException("This view only works with the NeutralTheoryModel class.");
		}
	
		int gen = ((NeutralTheoryModel) model).getGenerationNumber();
		
		if (gen == ((NeutralTheoryModel) model).getMaxGens()) {
		
			//species count history
			File file = new File("data/" + experimentTimeStamp + "/run" + Integer.toString(run.getRunNumber()) + "_speciesHistory.txt");
			BufferedWriter speciesHistoryWriter = new BufferedWriter(new FileWriter(file));
			
			List<Integer> speciesHistory = ((NeutralTheoryModel) model).getSpeciesCountHistory();
			
			speciesHistoryWriter.write("species.count\n");
			
			for (Integer speciesCount : speciesHistory) {
				speciesHistoryWriter.write(speciesCount + "\n");
			}
			
			speciesHistoryWriter.close();
	
			//final population
			storePopulation(Integer.toString(gen), run, (NeutralTheoryModel) model);
			
		} else if (gen % logPopulationInterval == 0) {
			storePopulation(Integer.toString(gen), run, (NeutralTheoryModel) model);
		}
	}
	
	private void storePopulation(String id, Run run, NeutralTheoryModel model) throws Exception {
		File file = new File("data/" + experimentTimeStamp + "/run" + Integer.toString(run.getRunNumber()) + "_population" + id + ".txt");
		BufferedWriter populationWriter = new BufferedWriter(new FileWriter(file));
		
		List<Critter> population = model.getPopulation();
		populationWriter.write("species\tx\ty");
		StringBuilder genomeHeaders = new StringBuilder();
		int genomeLength = ((BitSetCritter) population.get(0)).getGenomeLength();
		for (int i = 0; i < genomeLength; i++) {
			genomeHeaders.append("\t" + Integer.toString(i));
		}
		populationWriter.write(genomeHeaders + "\n");
		
		for (Critter critter : population) {
			
			populationWriter.write(Integer.toString(critter.getSpeciesIndex()));
			
			double[] loc = critter.getLocation();
			populationWriter.write("\t" + Double.toString(loc[0]) + "\t" + Double.toString(loc[1]));
			
			BitSetCritter bitSetCritter = (BitSetCritter) critter;
			BitSet genome = bitSetCritter.getGenome();
			
			StringBuilder genomeString = new StringBuilder();
			for (int i = 0; i < genomeLength; i++) {
				genomeString.append("\t" + (genome.get(i) ? "1" : "0"));
			}
			populationWriter.write(genomeString + "\n");
		}
		
		populationWriter.close();
	}
	

	@Override
	public void start() throws Exception {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");
		experimentTimeStamp = sdf.format(cal.getTime());
		File experimentDirectory = new File("data/" + experimentTimeStamp);//TODO allow specification of directory for data storage
		if (!experimentDirectory.mkdir()) {
			throw new IOException("Failed to create directory: " + experimentDirectory);
		}
		File file = new File("data/" + experimentTimeStamp + "/experiment.txt");
		responseOut = new BufferedWriter(new FileWriter(file));
	}

	@Override
	public void close() throws Exception {
		responseOut.close();
	}

	@Override
	public void handleRunStart(Run run) throws Exception {
		// Do nothing
	}

	@Override
	public void handleMessage(Run run, String msg) throws Exception {
		// Do nothing
		
	}

}
